#include "m01_spi.h"

namespace igslib
{
    m01_spi::m01_spi()
    {
        port = -1;
        wf = 10000000;
    }
    bool m01_spi::Open(ChipSelector cs)
    {
        bool rtn = false;
        port = static_cast<int>(cs);
        int result = spi_open(port,wf);
        if (result == 0)
        {
            rtn = true;
        }
        return rtn;
    }
    bool m01_spi::HalfDuplexReadWrite(char* tx_buf,int tx_len,char* rx_buf,int rx_len)
    {
        bool rtn = true;
        if(tx_len!=0)
        {
            int result = spi_rw(
                    port,
                    (unsigned char*)tx_buf,
                    NULL,
                    tx_len
                    );
            if (result != 0)
            {
                rtn = false;
            }				
        }
        if(rx_len!=0)
        {
            int result = spi_rw(
                    port,
                    NULL,
                    (unsigned char*)rx_buf,
                    rx_len
                    );
            if (result != 0)
            {
                rtn = false;
            }				
        }


        return rtn;
    }
    bool m01_spi::FullDuplexReadWrite(char* tx_buf,char* rx_buf,int len)
    {
        bool rtn = false;

        const int mbc = 20; // max bytes count
        std::stringstream ss;
        ss << __func__ << ">";
        ss << "len=" << len;
        ss << ",Tx=";
        for ( int i = 0 ; i < mbc ; ++i )
        {
            char tmp[4] = {0};
            sprintf(tmp,"%02x ",tx_buf[i]);
            if (i == (mbc-1))
            {
                sprintf(tmp,"%02x ",tx_buf[len-1]);
            }
            ss << std::string(tmp);
        }
        //util::Log("%s\n",ss.str().c_str());

        int result = spi_rw(
                port,
                (unsigned char*)tx_buf,
                (unsigned char*)rx_buf,
                len
                );
        ss.str("");
        ss << ",Rx=";
        for ( int i = 0 ; i < mbc ; ++i )
        {
            char tmp[4] = {0};
            sprintf(tmp,"%02x ",rx_buf[i]);
            if (i == (mbc-1))
            {
                sprintf(tmp,"%02x ",rx_buf[len-1]);
            }
            ss << std::string(tmp);
        }
        if (result == 0)
        {
            rtn = true;
        }
        //util::Log("(%d)%s\n",rtn,ss.str().c_str());
        return rtn;
    }
    void m01_spi::Close()
    {
        spi_close(port);
    }
};
